package com.example.springvue.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.example.springvue.common.annotation.LogAnnotation;
import com.example.springvue.common.annotation.PassToken;
import com.example.springvue.common.handler.AdminUserHeaderHodler;
import com.example.springvue.common.handler.NotExistException;
import com.example.springvue.common.jwt.JwtUtils;
import com.example.springvue.common.jwt.Md5Utils;
import com.example.springvue.common.returnthrow.Result;
import com.example.springvue.common.utils.CommonUtils;
import com.example.springvue.model.AdminUser;
import com.example.springvue.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Controller
public class LoginController {


    @Autowired
    AdminUserService adminUserService;

    /**
     * 用户登录：获取账号密码并登录，如果不对就报错，对了就返回用户的登录信息
     * 同时生成jwt返回给用户
     *
     * @return
     */
    @PassToken
    @ResponseBody
    @PostMapping(value = "/admin/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> Body) throws NotExistException {
        System.out.println(Body.get("password"));
        try{
            AdminUser adminUser =  adminUserService.getAdminUserInfo(Body.get("username"));
            if (adminUser==null){
                return Result.failure("用户不存在");
            }
            String password = Md5Utils.getMd5Code(Body.get("password") + adminUser.getSalt());
            System.out.println(password);
            if (!Objects.equals(adminUser.getPassword(),password)){
                return Result.failure("密码错误");
            }
            String jwtToken = JwtUtils.createToken(adminUser.getId(),adminUser.getUsername(),adminUser.getNickname(),"admin");
            //返回的用户信息
            Map<String ,Object> userInfo = new HashMap<String, Object>();
            userInfo.put("id",adminUser.getId());
            userInfo.put("nickname",adminUser.getNickname());
            userInfo.put("username",adminUser.getUsername());
            userInfo.put("email",adminUser.getEmail());
            userInfo.put("avatar",adminUser.getAvatar());
            userInfo.put("avatar2", CommonUtils.image(adminUser.getAvatar()));

            Map<String ,Object> map = new HashMap<String, Object>();
            map.put("token",jwtToken);
            map.put("user", userInfo);
            return Result.success("登录成功",map);
        }
        catch (NotExistException e)
        {
            throw new NotExistException(e.getMessage());
        }
    }
}
